package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dto.DataManager;

import model.User;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username, password;

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		DataManager dataManager = new DataManager();

		username = request.getParameter("username");
		password = request.getParameter("password");
		User aUser = new User();
		aUser.setRoleId(2);
		aUser.setUsername(username);
		aUser.setPassword(password);
		aUser.setEmail(request.getParameter("email"));
		aUser.setOwnMoney(0);
		if (dataManager.insertUser(aUser)) {
			session.setAttribute("username", username);
			session.setAttribute("userId",
					dataManager.getUserWithUserName(username));
			session.setAttribute("roleId", 2);

			response.sendRedirect("default.jsp");
		}

		else {
			response.sendRedirect("registerForm.jsp?err=true");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
